package com.wang;

import com.wang.service.IDemoService;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.concurrent.CompletableFuture;

public class AppTestGenericService {
    public static void main(String[] args) throws Exception{
        //创建服务应用对象实例
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        //设置应用程序信息
        referenceConfig.setApplication(new ApplicationConfig("dubbo-consumer"));
        //设置服务注册中心
        referenceConfig.setRegistry(new RegistryConfig("nacos://127.0.0.1:8848"));
        //设置服务接口和超时时间
        referenceConfig.setInterface("com.wang.service.IDemoService");
        referenceConfig.setTimeout(10000);
        //设置负载策略和集群容错策略
        //referenceConfig.setLoadbalance("myLoadBalance");
        //referenceConfig.setCluster("myBroadcast");
        //设置服务的版本号和分组
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dev");
        //设置为异步调用
        referenceConfig.setAsync(true);
        referenceConfig.setGeneric("true");

        GenericService genericService = ReferenceConfigCache.getCache().get(getKey("com.wang.service.IDemoService","dev","1.0.0"));
        if(genericService == null){
            genericService = ReferenceConfigCache.getCache().get(referenceConfig);
        }
        Object getMsg = genericService.$invoke("getMsg", new String[]{"java.lang.String"}, new Object[]{"wang"});
        System.out.println(getMsg);
        RpcContext.getContext().setAttachment("company","xiaomi");
        CompletableFuture<String> future = RpcContext.getContext().getCompletableFuture();//.getFuture();
        System.out.println(future.get());

    }

    public static  String getKey(String serviceName, String group, String version) {
        if (StringUtils.isBlank(serviceName)) {
            throw new IllegalArgumentException("No interface info in ReferenceConfig" + serviceName);
        } else {
            StringBuilder ret = new StringBuilder();
            if (!StringUtils.isBlank(group)) {
                ret.append(group).append("/");
            }
            ret.append(serviceName);
            if (!StringUtils.isBlank(version)) {
                ret.append(":").append(version);
            }
            return ret.toString();
        }
    }
}
